import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmfmap_example/http/http.dart';
import 'package:flutter_bmfmap_example/models/deviceinfomodel.dart';
import 'package:flutter_bmfmap_example/models/familyinfomodel.dart';
import 'package:flutter_bmfmap_example/models/marketinfomodel.dart';
import 'package:flutter_bmfmap_example/models/userinformodel.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/Equipment_message/Equipment_message.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/devicepages/Tvcard.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/devicepages/temanhumpage.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/devicepages/Tvpage2.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/devicepages/ledpage.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/devicepages/ledpage2.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/familypages/GlassmorphicSample.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/familypages/familypage.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/familypages/familytext.dart';
import 'package:flutter_bmfmap_example/pages/homepage/pages/roompage/roompage.dart';
import 'package:flutter_bmfmap_example/tool/HYSizeFit%20.dart';
import 'package:flutter_bmfmap_example/tool/tool.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:qrscan/qrscan.dart' as scanner;

// typedef MyCallBack = Function(int i); //自定义了一个 传String的函数类型

class HomePage extends StatefulWidget {
  HomePage({Key key, this.opendrawer}) : super(key: key);
  VoidCallback opendrawer;

//有参数的   先定义一个函数类型

  // MyCallBack onPress; //第二种:回调函数的签名，没有参数，也不返回数据。

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  var controller = new ScrollController();

  List myfamilylist = [];
  List devicelist = [];
  Timer _timer;
  @override
  void initState() {
    super.initState();
    // controller.addListener(() {});
    // _getfamily();
    // _getdevice();

    const timeout = const Duration(seconds: 1);
    _timer = Timer.periodic(timeout, (timer) {
      context.read<DeviceInfomodel>().init();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ListView(
        // controller: controller,
        children: [
          _buildsearchbar(),
          _buildmyfamily(),
          _buildmydevice(),
          _buildmyroom(),
          SizedBox(
            height: 120,
          ),
        ],
      ),
    );
  }

  _buildmyroom() {
    return Container(
      // padding: EdgeInsets.only(top: 16, left: 24, right: 24),
      child: Column(
        // mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 8.0, left: 32, right: 32),
            child: Row(
              children: [
                Text(
                  '我的房间',
                  style: TextStyle(
                    fontSize: 16,
                    letterSpacing: 1.6,
                  ),
                ),
                Spacer(),
                InkWell(
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => GlassmorphicSample()));
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Icon(Icons.more_horiz),
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 220,
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: [
                SizedBox(
                  width: 24,
                ),
                InkWell(
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) {
                        return RoomPage(); //返回的是需要跳转单页面
                      },
                    ));
                  },
                  child: Container(
                    margin: EdgeInsets.all(8),
                    width: 160,
                    decoration: new BoxDecoration(
                      color: Color.fromRGBO(236, 223, 255, 1),
                      borderRadius: new BorderRadius.circular((16.0)),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(left: 24, top: 32),
                          child: Text(
                            '客厅',
                            style: TextStyle(fontSize: 20, fontFamily: 'Noto'),
                          ),
                        ),
                        Center(
                          child: Image.asset(
                            'assets/images/common/room/客厅.png',
                            width: 150,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.all(8),
                  width: 160,
                  decoration: new BoxDecoration(
                    color: Color.fromRGBO(199, 239, 254, 1),
                    borderRadius: new BorderRadius.circular((16.0)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 24, top: 32),
                        child: Text(
                          '卧室',
                          style: TextStyle(fontSize: 20, fontFamily: 'Noto'),
                        ),
                      ),
                      Center(
                        child: Image.asset(
                          'assets/images/common/room/卧室.png',
                          width: 150,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.all(8),
                  width: 160,
                  decoration: new BoxDecoration(
                    color: Color.fromRGBO(142, 135, 255, 1),
                    borderRadius: new BorderRadius.circular((16.0)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 24, top: 32),
                        child: Text(
                          '厨房',
                          style: TextStyle(fontSize: 20, fontFamily: 'Noto'),
                        ),
                      ),
                      Center(
                        child: Image.asset(
                          'assets/images/common/room/厨房.png',
                          width: 150,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  width: 24,
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  _buildmydevice() {
    return Container(
      padding: EdgeInsets.only(top: 0, left: 24, right: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  '我的设备',
                  style: TextStyle(
                    fontSize: 16,
                    letterSpacing: 1.6,
                  ),
                ),
              ),
              Spacer(),
              InkWell(
                onTap: () {
                  scan();
                  // Navigator.push(context,
                  //     MaterialPageRoute(builder: (context) => familyText()));
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Icon(Icons.more_horiz),
                ),
              ),
            ],
          ),
          // Row(
          //   children: [
          //     _builddeviceitem('监控', Color.fromRGBO(149, 140, 255, 1), 1),
          //     _builddeviceitem('空调', Color.fromRGBO(125, 232, 194, 1),
          //         devicelist.length == 0 ? 0 : devicelist[5]['list'].length),
          //   ],
          // ),
          // Row(
          //   children: [
          //     _builddeviceitem('门锁', Color.fromRGBO(254, 124, 91, 1),
          //         devicelist.length == 0 ? 0 : devicelist[2]['list'].length),
          //     _builddeviceitem('灯泡', Color.fromRGBO(249, 169, 255, 1),
          //         devicelist.length == 0 ? 0 : devicelist[0]['list'].length),
          //   ],
          // ),
          // Row(
          //   children: [
          //     _builddeviceitem('窗帘', Color.fromRGBO(93, 154, 248, 1),
          //         devicelist.length == 0 ? 0 : devicelist[1]['list'].length),
          //     _builddeviceitem('温湿度表', Color.fromRGBO(255, 231, 119, 1),
          //         devicelist.length == 0 ? 0 : devicelist[6]['list'].length),
          //   ],
          // ),
          // Row(
          //   children: [
          //     _builddeviceitem('电视', Color.fromRGBO(150, 50, 248, 1),
          //         devicelist.length == 0 ? 0 : devicelist[4]['list'].length),
          //     _builddeviceitem('烟雾报警', Color.fromRGBO(255, 160, 200, 1),
          //         devicelist.length == 0 ? 0 : devicelist[3]['list'].length),
          //   ],
          // ),

          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              height: 300,
              child: GridView(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    //横轴元素个数
                    crossAxisCount: 2,
                    //纵轴间距
                    mainAxisSpacing: 8.0,
                    //横轴间距
                    // crossAxisSpacing: 16.0,
                    //子组件宽高长度比例
                    childAspectRatio: 2),
                children: _builddevicelist(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _builddevicelist() {
    List<Widget> list = [];
    for (int i = 1; i <= 8; i++) {
      int num = context.watch<DeviceInfomodel>().getnumbyType(i);

      if (num > 0) {
        list.add(_builddeviceitem(num, i));
      }
    }
    return list;
  }

  _buildmyfamily() {
    return Container(
      padding: EdgeInsets.only(top: 16, left: 24, right: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  '我的家人',
                  style: TextStyle(
                    fontSize: 16,
                    letterSpacing: 1.6,
                  ),
                ),
              ),
              Spacer(),
              InkWell(
                onTap: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => familyText()));
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Icon(Icons.more_horiz),
                ),
              ),
            ],
          ),
          Container(
            height: 96,
            child: ListView.builder(
              itemCount: context.watch<FamilyInfomodel>().familylist.length,
              // itemExtent: 50.0,
              scrollDirection: Axis.horizontal,
              itemBuilder: (BuildContext context, int index) {
                return _buildfamilycard(index);
              },
            ),
          )
        ],
      ),
    );
  }

  _buildfamilycard(int index) {
    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => GlassmorphicSample(
                personinfo: context.watch<FamilyInfomodel>().familylist[index],
                index: index),
          ),
        );
      },
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 8, right: 8),
            child: Container(
              height: 72,
              width: 72,
              child: Center(
                child: Hero(
                  tag:
                      context.watch<FamilyInfomodel>().familylist[index].logoId,
                  child: Image.asset(
                    Tool.getportrait(context
                        .watch<FamilyInfomodel>()
                        .familylist[index]
                        .logoId),
                    width: 80,
                  ),
                ),
              ),
            ),
          ),
          Text(context.watch<FamilyInfomodel>().familylist[index].personName),
        ],
      ),
    );
  }

  _buildsearchbar() {
    return Container(
      margin: EdgeInsets.only(top: 16, left: 28, right: 28),
      height: 56,
      // decoration: new BoxDecoration(
      //   color: Colors.white,
      //   borderRadius: new BorderRadius.circular((16.0)),
      //   boxShadow: [
      //     BoxShadow(
      //         color: Colors.black12,
      //         offset: Offset(0.0, 0.0), //阴影xy轴偏移量
      //         blurRadius: 5.0, //阴影模糊程度
      //         spreadRadius: 0.1 //阴影扩散程度
      //         ),
      //   ],
      // ),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              widget.opendrawer();
            },
            child: Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 8.0, right: 8),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(22),
                    child: Image.network(
                      context.watch<Userinfomodel>().getportraiturl(),
                      // color: Colors.black54,
                      width: 44,
                    ),
                  ),
                ),
                SizedBox(
                  width: 8,
                ),
                Text(
                  context.watch<Userinfomodel>().getnickname(),
                ),
                SizedBox(
                  width: 8,
                ),
                Padding(
                  padding: const EdgeInsets.all(6.0),
                  child: Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                  ),
                ),
              ],
            ),
          ),
          Spacer(),
          GestureDetector(
            onTap: () {
              print('弹出');
              new PopupMenuButton(
                  onSelected: (String value) {
                    setState(() {
                      // _bodyStr = value;
                    });
                  },
                  itemBuilder: (BuildContext context) =>
                      <PopupMenuItem<String>>[
                        new PopupMenuItem(
                            value: "选项一的内容", child: new Text("选项一")),
                        new PopupMenuItem(
                            value: "选项二的内容", child: new Text("选项二"))
                      ]);
              setState(() {});
            },
            child: InkWell(
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Equipment_message()));
              },
              child: Container(
                width: 44,
                height: 44,
                decoration: new BoxDecoration(
                  color: Colors.white,
                  borderRadius: new BorderRadius.circular((12.0)),
                  boxShadow: [
                    BoxShadow(
                        color: Colors.black12,
                        offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                        blurRadius: 5.0, //阴影模糊程度
                        spreadRadius: 0.1 //阴影扩散程度
                        ),
                  ],
                ),
                child: Center(
                  child: SvgPicture.asset(
                    "assets/images/icons/svg/消息.svg",
                    color: Colors.black54,
                    width: 28,
                  ),
                ),
              ),
            ),
          ),
          SizedBox(
            width: 8,
          ),
        ],
      ),
    );
  }

  Widget _builddeviceitem(int num, int type) {
    String name;
    Color color;
    if (type == 1) {
      name = '灯泡';
      color = Color.fromRGBO(249, 169, 255, 1);
    } else if (type == 2) {
      name = '窗帘';
      color = Color.fromRGBO(93, 154, 248, 1);
    } else if (type == 3) {
      name = '门锁';
      color = Color.fromRGBO(254, 124, 91, 1);
    } else if (type == 4) {
      name = '烟雾报警';
      color = Color.fromRGBO(255, 160, 200, 1);
    } else if (type == 5) {
      name = '电视';
      color = Color.fromRGBO(150, 50, 248, 1);
    } else if (type == 6) {
      name = '空调';
      color = Color.fromRGBO(125, 232, 194, 1);
    } else if (type == 7) {
      name = '温湿度表';
      color = Color.fromRGBO(255, 231, 119, 1);
    } else {
      name = '监控';
      color = Color.fromRGBO(149, 140, 255, 1);
    }
    return InkWell(
      onTap: () {
        if (name == "灯泡")
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => LedPage2(),
            ),
          );
        else if (name == "电视")
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => TvPage2(),
            ),
          );
        else if (name == "温湿度表")
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => TemandHumPage(),
            ),
          );
      },
      child: Container(
        height: 60,
        // width:140,
        margin: EdgeInsets.all(8),
        decoration: new BoxDecoration(
          color: color,
          borderRadius: new BorderRadius.circular((16.0)),
        ),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 16, right: 8),
              child: SvgPicture.asset(
                "assets/images/icons/svg/$name.svg",
                color: Colors.white,
                width: 32,
              ),
            ),
            Text(
              name,
              style: TextStyle(color: Colors.white),
            ),
            Spacer(),
            Text(
              num.toString(),
              style: TextStyle(color: Colors.white, fontSize: 18),
            ),
            SizedBox(
              width: 16,
            ),
          ],
        ),
      ),
    );
  }
}

//扫码函数,最简单的那种
Future scan() async {
  // String cameraScanResult = await scanner.scan(); //通过扫码获取二维码中的数据
  // cameraScanResult = "";
  // getScan(cameraScanResult); //将获取到的参数通过HTTP请求发送到服务器
  // print(cameraScanResult); //在控制台打印
}

//get请求，用于验证数据(也可以在控制台直接打印，但模拟器体验不好)
void getScan(String scan) async {
  // var url="http://164.155.66.12/GetScan?scan="+scan;
  // var dio = Dio();
  // var response = await dio.get(url);
  // var data = response.data.toString();
  // print(data);
}
